package com.arpa.wms.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.arpa.core.web.MediaTypes;
import com.arpa.core.web.Result;
import com.arpa.ntocc.common.common.Page;
import com.arpa.ntocc.common.common.cache.ShipmentCache;
import com.arpa.ntocc.common.common.constant.StrConsts;
import com.arpa.ntocc.common.common.exception.ServiceException;
import com.arpa.ntocc.common.common.util.UserUtil;
import com.arpa.ntocc.common.security.annotation.NeedLogin;
import com.arpa.wms.domain.consts.CommonConst;
import com.arpa.wms.domain.consts.NumConst;
import com.arpa.wms.domain.dto.ShopDTO;
import com.arpa.wms.domain.dto.ShopauditDTO;
import com.arpa.wms.domain.entity.Shop;
import com.arpa.wms.domain.enums.DeleteStatusEnum;
import com.arpa.wms.domain.vo.ShopVO;
import com.arpa.wms.service.IShopService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.*;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;


/**
 * <p>
 * 店铺 Controller
 * </p>
 *
 * @author LEO
 * @since 2021-2-22
 */
@Api(tags = "店铺管理")
@RestController
@RequestMapping(value = "/shop", produces = "application/json;charset=UTF-8")
@Log4j2
public class ShopController {

    private final IShopService iShopService;
    @Autowired
    private ShipmentCache shipmentCache;
    public ShopController(IShopService iShopService) {
        this.iShopService = iShopService;
    }

    /**
     * 获取 店铺 列表
     *
     * @param shopDTO
     * @param request
     * @return
     */
    @ApiOperation(value = "获取 店铺 列表", notes = "获取 店铺 列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = ShopVO.class))
    @NeedLogin
    @PostMapping("/list")
    public Result list(ShopDTO shopDTO, HttpServletRequest request) {
        try {
            shopDTO.setGroupCode(UserUtil.getBranchCode());
            ShopVO shopVoSum = iShopService.queryListSum(shopDTO);
            List<ShopVO> shopVOList = iShopService.queryList(shopDTO);

            Page returnPage = new Page(shopDTO.getPageNum(), shopDTO.getPageSize());
            returnPage.setRecords(shopVOList);
            returnPage.setTotal(shopVoSum.getTotal());
            returnPage.setSumObject(shopVoSum);
            return Result.ok().data(returnPage);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 添加 店铺
     *
     * @param entity  Warehouse
     * @param request
     * @return
     */
    @ApiOperation(value = "添加 店铺 ", notes = "添加 店铺 ")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PostMapping("/save")
    public Result insert(@RequestBody @Validated(Shop.Save.class) Shop entity, HttpServletRequest request) {
        try {
            entity.setGroupCode(UserUtil.getBranchCode());
            iShopService.insert(entity);
            return Result.ok("添加成功");
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取店铺详情
     *
     * @param code
     * @param request
     * @return
     */
    @ApiOperation(value = "获取店铺详情", notes = "获取店铺详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "code", value = "店铺code", paramType = "path", dataType = "String")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = Shop.class))
    @NeedLogin
    @GetMapping(value = "/{code}")
    public Result shop(@PathVariable String code, HttpServletRequest request) {
        try {
            ShopVO shopVO = iShopService.getOneInfo(code);
            return Result.ok().data(shopVO);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }


    /**
     * 修改店铺
     *
     * @param entity  店铺
     * @param request
     * @return
     */
    @ApiOperation(value = "修改店铺", notes = "修改店铺")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PutMapping()
    public Result update(@RequestBody @Validated(Shop.Update.class) Shop entity, HttpServletRequest request) {

        if (StrUtil.isBlank(entity.getCode())) {
            return Result.error("code不能为空");
        }
            int updateNum = iShopService.update(entity);
            if (updateNum == 0) {
                return Result.error("没有更新数据！code:" + entity.getCode());
            } else {
                return Result.ok("修改成功,更新" + updateNum + "条数据！");
            }

    }


    /**
     * 删除 店铺
     *
     * @param codes
     * @param request
     * @return
     */
    @ApiOperation(value = "删除 店铺 ", notes = "删除 店铺 ", produces = MediaTypes.JSON_UTF_8)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "codes", value = "codes", required = true, paramType = "header", dataType = "String"),
    })
    @NeedLogin
    @GetMapping(value = "")
    public Result batchdel(@RequestParam(value="codes") String codes, HttpServletRequest request) {
        try {
            String groupCode = UserUtil.getBranchCode();
            iShopService.remove(new QueryWrapper<Shop>().lambda().in(Shop::getCode,codes).eq(Shop::getGroupCode,groupCode));
            return Result.ok();
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }



    /**
     * WMS业务操作获取店铺数据
     *
     * @param request
     * @return
     */
    @ApiOperation(value = "WMS业务操作获取店铺数据", notes = "仅限WMS业务操作页面下拉框使用")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "shipmentCode", value = "入驻商code", paramType = "param", dataType = "String"),
            @ApiImplicitParam(name = "sourcePlatformCode", value = "平台类型", paramType = "param", dataType = "String")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = ShopVO.class))
    @NeedLogin
    @GetMapping("/shopList")
    public Result businessChooseData(ShopDTO shopDTO,
            HttpServletRequest request) {
        String groupCode = UserUtil.getBranchCode();
        if(StrUtil.isBlank(groupCode)){
            throw new ServiceException("用户所属组织为空，请重新登录");
        }
        shopDTO.setGroupCode(groupCode);
        shopDTO.setStatus(CommonConst.STR_ONE);
        shopDTO.setPageSize(NumConst.NUM_NINETY_NINE_THOUSAND_NINE_HUNDRED_NINETY_NINE);
        List<ShopVO> shopVOList = iShopService.queryList(shopDTO);
        //获取云仓对应平台的店铺,如果存在，将其放到最前面
        Shop shop = iShopService.getOne(new LambdaQueryWrapper<Shop>()
                .eq(Shop::getSourcePlatformCode, shopDTO.getSourcePlatformCode())
                .eq(Shop::getRemark,"云仓店铺")
                .eq(Shop::getGroupCode,groupCode)
        );
        if (null != shop) {
            ShopVO shopVO = new ShopVO();
            BeanUtil.copyProperties(shop,shopVO);
            shopVOList.add(NumConst.NUM_ZERO,shopVO);
        }
        return Result.ok().data(shopVOList);
    }

}
